﻿/*
==============================================================================
//  角色权限管理 的页面控制层代码。
==============================================================================
*/
(function ($) {

    $.util.namespace("views.Role.PermissionManage");

    var tree = "#tree1", tg = "#tg"; var lastNodeId;

    window.views.Role.PermissionManage.initPage = function (permissions) {
        var data = window.jeasyui.helper.buildToolbarUsePermissionJson(permissions, true);
        data.push({ type: "button", options: { text: "刷新", iconCls: "icon-reload", onclick: function (t) { window.views.Role.reloadPermissionAndOtherRole(); } } });

        var initTreeReloadButton = function () {
            var toolbar = $("<div />").insertBefore(tree).toolbar({
                data: [{
                    type: "button", options: {
                        text: "刷新", iconCls: "icon-reload", onclick: function (t) {
                            var oldNode = $(tree).tree("getSelected");
                            if (oldNode) { lastNodeId = oldNode.id; }
                            $(tree).tree("reload");
                        }
                    }
                }]
            }).toolbar("toolbar");
        };

        var treeInit = function () {

            var options = {
                url: "/Public/OrganizationRoleJson",
                animate: true,
                toggleOnClick: true,
                onBeforeSelect: function (node) {
                    return node.attributes.IsRole;
                },
                onSelect: function (node) {
                    $(tg).treegrid("getPanel").panel("setTitle", "[" + node.text + "] - 角色权限设置");
                    window.views.Role.reloadPermissionAndOtherRole(node.attributes.RoleID);
                },
                onBeforeLoad: function (node, param) {
                    $.easyui.loading({ locale: $(this).currentRegion(), msg: "数据加载中..." });
                },
                onLoadSuccess: function (node) {
                    var t = $(this);
                    $.easyui.loaded(t.currentRegion());
                    if (!$.string.isNullOrWhiteSpace(lastNodeId)) {
                        var lastNode = t.tree("find", lastNodeId);
                        if (lastNode) { t.tree("select", lastNode.target); }
                    }
                    if (node == null) {
                        t.tree("expandAll");
                    }
                }
            };

            $(tree).tree(options);
        };

        var treeGridInit = function () {
            var toolbar = $("<div />").appendTo("body").toolbar({
                data: data
            }).toolbar("toolbar");

            var frozenColumns = function (showCheckBox) {
                var result = [];
                if (showCheckBox) {
                    result.push({ field: 'ck', checkbox: true });
                }
                var normal = [{ field: 'Name', title: '菜单', width: 200 }];
                $.util.merge(result, normal);
                return result;
            };

            var columns = function (sortableEnable) {
                var result = [];
                var normal = [
                        {
                            field: 'Permission', title: '权限', width: 1300, align: "left",
                            formatter: function (val, row) {
                                var html = "";
                                if (row.Permissions && row.Permissions.length && row.Permissions.length > 0) {
                                    $.each(row.Permissions, function (i, p) {
                                        html += "<span id=\"checkspan_" + p.MenuPermissionID + "_end\" name=\"checkspan_" + row.ID + "_end\" class=\"tree-checkbox tree-checkbox" + p.State + "\" key=\"" + p.MenuPermissionID + "\" value=\"" + row.ID + "\" onclick=\"window.views.Role.checkState(this, event);\" ></span><b>" + p.MenuPermissionName + "</b>&nbsp;&nbsp;&nbsp;&nbsp;";
                                    });
                                }
                                return html;
                            }
                        },
                ];
                if (sortableEnable) {
                    $.array.forEach(normal, function (val, index, array) {
                        val.sortable = true;
                    });
                }
                $.util.merge(result, normal);
                return result;
            };

            var options = {
                title: "角色权限设置",
                idField: "ID",
                treeField: "Name",
                dataPlain: true,
                parentField: "ParentID",
                toolbar: toolbar,
                rownumbers: true,
                fit: true,
                border: false,
                singleSelect: true,
                checkOnSelect: false,
                selectOnCheck: false,
                cascadeCheck: true,
                enableHeaderClickMenu: false,
                frozenColumns: [frozenColumns(true)],
                columns: [columns(false)],
                onCheck: function (rowData) {
                    var dom = $(this).treegrid("getRowDom", rowData.ID);
                    $("span[name='checkspan_" + rowData.ID + "_end']", dom).removeClass("tree-checkbox0 tree-checkbox2").addClass("tree-checkbox1");
                },
                onUncheck: function (rowData) {
                    var dom = $(this).treegrid("getRowDom", rowData.ID);
                    $("span[name='checkspan_" + rowData.ID + "_end']", dom).removeClass("tree-checkbox1 tree-checkbox2").addClass("tree-checkbox0");
                },
                onCheckAll: function (rows) {
                    var dgPanel = $(this).treegrid("getPanel");
                    $("span[id^='checkspan_']", dgPanel).removeClass("tree-checkbox0 tree-checkbox2").addClass("tree-checkbox1");
                },
                onUncheckAll: function (rows) {
                    var dgPanel = $(this).treegrid("getPanel");
                    $("span[id^='checkspan_']", dgPanel).removeClass("tree-checkbox1 tree-checkbox2").addClass("tree-checkbox0");
                }
            };

            $(tg).treegrid(options);
        };

        initTreeReloadButton();
        treeInit();
        treeGridInit();
    };


    window.views.Role.checkState = function (ck, e) {
        ck = $(ck);
        if (ck.hasClass("tree-checkbox0")) {
            ck.removeClass("tree-checkbox0").addClass("tree-checkbox1");
        }
        else if (ck.hasClass("tree-checkbox1")) {
            ck.removeClass("tree-checkbox1").addClass("tree-checkbox0");
        }
        //else {
        //    ck.removeClass("tree-checkbox2").addClass("tree-checkbox1");
        //}
        e.stopPropagation();
    };

    window.views.Role.reloadPermissionAndOtherRole = function (roleId, reloadTree) {
        if (!roleId) { var selectRole = $(tree).tree("getSelected"); if (selectRole && selectRole.attributes.IsRole) { roleId = selectRole.attributes.RoleID; } }
        reloadTree = reloadTree ? reloadTree : false;
        if (roleId) {
            $.easyui.loading({ locale: $("body"), msg: "数据处理中，请稍等..." });
            $.post("/Role/RoleMenuPermissionJson", { roleId: roleId }, function (data) {
                $.easyui.loaded($("body"));
                $(tg).treegrid("clearSelections");
                $(tg).treegrid("clearChecked");
                $(tg).treegrid("loadData", data);
            });
            //if (reloadTree) { $(roleTreeOther).tree("reload"); }
        }
    };

    window.views.Role.saveRolePermission = function (showOther) {
        var selectRole = $(tree).tree("getSelected");
        if (selectRole && selectRole.attributes.IsRole) {
            var dgPanel = $(tg).treegrid("getPanel");
            var currentRowCheckbox = $("span[id^='checkspan_']", dgPanel);
            var arrayPermission = [];
            currentRowCheckbox.each(function (i, el) {
                var check = !$(el).hasClass("tree-checkbox0");
                arrayPermission.push({ MenuID: $(el).attr("value"), MenuPermissionID: $(el).attr("key"), Check: check });
            });

            var param = { permission: JSON.stringify(arrayPermission), roleId: selectRole.attributes.RoleID };
            if (!showOther) {
                //var otherselectRole = $(roleTreeOther).tree("getChecked");
                //var otherRoleId = [];
                //$.array.forEach(otherselectRole, function (val) {
                //    if (val.attributes.IsRole) {
                //        otherRoleId.push(val.attributes.ID);
                //    }
                //});

                //$.extend(param, { otherRoleIds: otherRoleId.join(",") });
            }
            $.easyui.loading({ locale: $("body"), msg: "数据处理中，请稍等..." });
            $.post("/Role/SaveRolePermission", param, function (result) {
                $.easyui.loaded($("body"));
                window.jeasyui.helper.actionDoneCallBack.call(this, result);
            });
        }
    };

})(jQuery);